<template>
  <div
    style="
      width: 99%;
      height: 85vh;
      display: flex;
      flex-wrap: wrap;
      background-color: #000;
    "
  >
    <div
      v-for="i in spilt"
      :key="i"
      class="play-box"
      :style="liveStyle"
      :class="{ redborder: playerIdx == i - 1 }"
      @click="playerIdx = i - 1"
    >
      <div
        v-if="!videoUrl[i - 1]"
        style="color: #ffffff; font-size: 30px; font-weight: bold"
      >
        {{ i }}
      </div>
      <player
        ref="player"
        v-else
        :videoUrl="videoUrl[i - 1]"
        fluent
        autoplay
        @screenshot="shot"
        @destroy="destroy"
      />
    </div>
  </div>
</template>
<script>
import player from "./common/player.vue";
import axios from 'axios';
export default {
  name: "live",
  components: {
    player,
  },
  data() {
    return {
      videoUrl: [""],
      videoList:[],
      spilt: 9, //分屏
      playerIdx: 0, //激活播放器

      updateLooper: 0, //数据刷新轮训标志
      count: 15,
      total: 0,

      //channel
      loading: false,
    };
  },
  mounted() {},
  created() {
    // this.checkPlayByParam();
    //获取视频列表
    this.getList();
  },

  computed: {
    liveStyle() {
      let style = { width: "100%", height: "100%" };
      switch (this.spilt) {
        case 4:
          style = { width: "49%", height: "49%" };
          break;
        case 9:
          style = { width: "32%", height: "32%" };
          break;
      }
      this.$nextTick(() => {
        for (let i = 0; i < this.spilt; i++) {
          const player = this.$refs.player;
          player && player[i] && player[i].updatePlayerDomSize();
        }
      });
      return style;
    },
  },
  watch: {
    spilt(newValue) {
      console.log("切换画幅;" + newValue);
      let that = this;
      for (let i = 1; i <= newValue; i++) {
        if (!that.$refs["player" + i]) {
          continue;
        }
        this.$nextTick(() => {
          if (that.$refs["player" + i] instanceof Array) {
            that.$refs["player" + i][0].resize();
          } else {
            that.$refs["player" + i].resize();
          }
        });
      }
      window.localStorage.setItem("split", newValue);
    },
    "$route.fullPath": "checkPlayByParam",
  },
  destroyed() {
    clearTimeout(this.updateLooper);
  },
  methods: {
    getList() {
    //  console.log("this",this.$axios.post());

    axios({
         method: 'post',
          url: "http://120.79.247.99:7070/swater-agd/camera/cameraList",
          data: {
            limit: 9,
            orgId: "",
            page: 1,
          },
          headers: {
              'Content-Type': 'application/json;charset=utf-8;application/vnd.ms-excel',
              'Accept': '*/*',
              'token': "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MzA4NzQ5NTcsInVzZXJuYW1lIjoiYWRtaW4ifQ.AYueROKqhGRdKDA4UiYBfXTJSGaGuhcibcHiqRCyC_E",
          },
        })
        .then((res) => {
          if(res.data.code == 0){
            this.videoList = res.data.data.list;
            console.log("this.videoList",this.videoList);
          }
        });
    },

    destroy(idx) {
      console.log(idx);
      this.clear(idx.substring(idx.length - 1));
    },
    clickEvent: function (device, data, isCatalog) {
      if (data.channelId && !isCatalog) {
        if (device.online === 0) {
          this.$message.error("设备离线!不允许点播");
        } else {
          this.sendDevicePush(data);
        }
      }
    },
    contextMenuEvent: function (device, event, data, isCatalog) {},
    //通知设备上传媒体流
    sendDevicePush: function (itemData) {
      // if (itemData.status === 0) {
      //   this.$message.error('设备离线!');
      //   return
      // }
      this.save(itemData);
      let deviceId = itemData.deviceId;
      // this.isLoging = true;
      let channelId = itemData.channelId;
      console.log("通知设备推流1：" + deviceId + " : " + channelId);
      let idxTmp = this.playerIdx;
      let that = this;
      this.loading = true;
      this.$axios({
        method: "get",
        url: "/api/play/start/" + deviceId + "/" + channelId,
      })
        .then(function (res) {
          if (res.data.code === 0 && res.data.data) {
            let videoUrl;
            if (location.protocol === "https:") {
              videoUrl = res.data.data.wss_flv;
            } else {
              videoUrl = res.data.data.ws_flv;
            }
            itemData.playUrl = videoUrl;
            that.setPlayUrl(videoUrl, idxTmp);
          } else {
            that.$message.error(res.data.msg);
          }
        })
        .catch(function (e) {})
        .finally(() => {
          that.loading = false;
        });
    },
    setPlayUrl(url, idx) {
      this.$set(this.videoUrl, idx, url);
      let _this = this;
      setTimeout(() => {
        window.localStorage.setItem("videoUrl", JSON.stringify(_this.videoUrl));
      }, 100);
    },
    checkPlayByParam() {
      let { deviceId, channelId } = this.$route.query;
      if (deviceId && channelId) {
        this.sendDevicePush({ deviceId, channelId });
      }
    },
    shot(e) {
      // console.log(e)
      // send({code:'image',data:e})
      var base64ToBlob = function (code) {
        let parts = code.split(";base64,");
        let contentType = parts[0].split(":")[1];
        let raw = window.atob(parts[1]);
        let rawLength = raw.length;
        let uInt8Array = new Uint8Array(rawLength);
        for (let i = 0; i < rawLength; ++i) {
          uInt8Array[i] = raw.charCodeAt(i);
        }
        return new Blob([uInt8Array], {
          type: contentType,
        });
      };
      let aLink = document.createElement("a");
      let blob = base64ToBlob(e); //new Blob([content]);
      let evt = document.createEvent("HTMLEvents");
      evt.initEvent("click", true, true); //initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
      aLink.download = "截图";
      aLink.href = URL.createObjectURL(blob);
      aLink.click();
    },
    save(item) {
      let dataStr = window.localStorage.getItem("playData") || "[]";
      let data = JSON.parse(dataStr);
      data[this.playerIdx] = item;
      window.localStorage.setItem("playData", JSON.stringify(data));
    },
    clear(idx) {
      let dataStr = window.localStorage.getItem("playData") || "[]";
      let data = JSON.parse(dataStr);
      data[idx - 1] = null;
      console.log(data);
      window.localStorage.setItem("playData", JSON.stringify(data));
    },
  },
};
</script>
<style lang="scss" scoped>
.live {
  width: 1920px;
  height: 900px;
  background-color: saddlebrown;
}
</style>
